﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

using University.Workshop.DataAccess;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Controls;
namespace University.Workshop.Model
{
    public class ClientManager
    {

        private DatabaseQuery DataBase = new DatabaseQuery();
        TcpClient tcpClient; 
        public string Address { get; set; }
        public NetworkStream ClientStream{get;set;}
        User user;
        public string VerifyPass { get; set; }
    
        public bool Busy { get; set; }
        public bool CommunicationOff{get;set;}
        public int TableNumber { get; set; }
        public int MyId{get;set;}
        //[CLSCompliantAttribute(false)]
        //public Collection<NetworkStream> Partners { get; set; }
        //[CLSCompliantAttribute(false)]
        //public Collection<NetworkStream> ChatPartners = new Collection<NetworkStream>();
        public string Parameter { get; set; }
        public string Parameter2 { get; set; }

        public string ParameterCard { get; set; }
        public bool Delete { get; set; }
        private TextBox text;
        //Empty Constructor
        //TableManager A = TableManager.Instance;
        DatabaseQuery Query = new DatabaseQuery();

        public string CaseSwitchGlobal{get; set;}

        public ClientManager()
        {
         //   StringManager = new ResourceManager("en-US", Assembly.GetExecutingAssembly());
            //Partners = new Collection<NetworkStream>();
            Busy = false;
          }

        //Constructor recives a client 
        public ClientManager(TcpClient clientReceived,int port,TextBox newText)
        {
            text = newText;
            //Partners = new Collection<NetworkStream>();
            Busy = false;
            if (port < 3000)
            {
                TableNumber = 3000 - port - 1;
               }
                tcpClient = clientReceived;
                if (tcpClient != null)
                {
                    ClientStream = tcpClient.GetStream();
                    }
        }

        //
        public void DisconnectClient()
        {
           // chatPartners.Remove(chatPartners[MyID]);
            CommunicationOff = true;
        }

        //receive client answer
        public string Receive()
        {
            byte[] messageBytes = new byte[4028];
            int bytesReaded = 0;
            string messageString;

            try
            {

                bytesReaded = ClientStream.Read(messageBytes, 0, 4028);
                ClientStream.Flush();
                if (bytesReaded == 0)
                    DisconnectClient();
                else
                {
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    messageString = encoder.GetString(messageBytes, 0, bytesReaded);

                    //System.Diagnostics.Debug.WriteLine(mensaje);
                    return messageString;

                }
            }
            catch (ArgumentNullException)
            {
                DisconnectClient();
                GlobalString.Instance.Message =Resources.message1;
            }
            catch (ArgumentOutOfRangeException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }
            catch (IOException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }
            catch (ObjectDisposedException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }



            return null;
        }

        //sends answer to client
        public void Send(string message)
        {
            try
            {
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(message);
                ClientStream.Write(buffer, 0, buffer.Length);
                ClientStream.Flush();
            }
            catch (IOException) { }
        }

        //to Wait answer , to Send answer to Client
/*        public string[] SeparateString(string all)
        {
            if (all == null)
                throw new ArgumentNullException("all");
            char space = ' ';
            string[] text = all.Split(space);
            return text;
        }*/
        public byte[] ReceiveImage(int height)
        {
            if (height == 0)
                return null;
            byte[] picture = new byte[height];
            int bytesReaded = 0;

            try
            {
                bytesReaded = ClientStream.Read(picture, 0, height);
                ClientStream.Flush();
                if (bytesReaded == 0)
                    DisconnectClient();
                else
                {

                    return picture;

                }

            }
            catch (ArgumentNullException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }
            catch (ArgumentOutOfRangeException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }
            catch (IOException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }
            catch (ObjectDisposedException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }

            return null;
        }
        public bool JoinToTheTable(string name,string chips,int level,int timeHandWon, string playersLimit)
        {
            //send("ok");
            int PlayersLimit;
            try
            {
                PlayersLimit = Convert.ToInt16(playersLimit, CultureInfo.CurrentCulture);
            }
            catch (FormatException)
            {
                return (false);
            }


            if (TableManager.Instance.Tables[TableNumber].Users == PlayersLimit || TableManager.Instance.Tables[0].IsStart) return false;
            TableManager.Instance.Tables[TableNumber].Partners.Add(ClientStream);
              
            TableManager.Instance.Tables[TableNumber].UserTable[TableManager.Instance.Tables[TableNumber].Users] = name;
            TableManager.Instance.Tables[TableNumber].Chips[TableManager.Instance.Tables[TableNumber].Users] = chips;
            TableManager.Instance.Tables[TableNumber].Level[TableManager.Instance.Tables[TableNumber].Users] = level;
            TableManager.Instance.Tables[TableNumber].TimeHandsWon[TableManager.Instance.Tables[TableNumber].Users] = timeHandWon;
            TableManager.Instance.Tables[TableNumber].Users++;
            return true;
        }
        public void SendUser(int userId)
        {
            Receive();
            this.Parameter = TableManager.Instance.Tables[TableNumber].UserTable[userId] + " " + TableManager.Instance.Tables[TableNumber].Chips[userId] + " " + TableManager.Instance.Tables[TableNumber].Level[userId]+" "+TableManager.Instance.Tables[TableNumber].TimeHandsWon[userId];
            Send(this.Parameter);
          
          }
        public void SendBytes(byte[] message)
        {
            try {
                if (message == null)
                    throw new ArgumentNullException("message");
                byte[] buffer = message;
                ClientStream.Write(buffer, 0, buffer.Length);
                ClientStream.Flush();

            }
            catch (ArgumentNullException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }
            catch (ArgumentOutOfRangeException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }
            catch (IOException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }
            catch (ObjectDisposedException)
            {
                DisconnectClient();
                GlobalString.Instance.Message = Resources.message1;
            }

            

        }
        [CLSCompliantAttribute(false)]
        public void SendToAllUsers(Collection<NetworkStream> userList)
        {
            int ID = TableManager.Instance.Tables[TableNumber].Users-1 ;
            MyId=ID;
            if(userList==null)
                throw new ArgumentNullException("userList");
            //Partners = userList;
            if (MyId < 5)
            {
                byte[] buffer;
                byte[] messageBytes;
                int value = 0;
                foreach (NetworkStream PartnerUser in userList)
                {
                    if (value < ID)
                    {
                        ASCIIEncoding encoder = new ASCIIEncoding();

                        this.Parameter = "01 " + TableManager.Instance.Tables[TableNumber].UserTable[ID] + " " + TableManager.Instance.Tables[TableNumber].Chips[ID] + " " + TableManager.Instance.Tables[TableNumber].Level[ID] + " " + TableManager.Instance.Tables[TableNumber].TimeHandsWon[ID];
            

                        buffer = encoder.GetBytes(this.Parameter);
                        PartnerUser.Write(buffer, 0, buffer.Length);
                        PartnerUser.Flush();
                        messageBytes = new byte[4046];
                        PartnerUser.Read(messageBytes, 0, 4046);
                        value++;
                    }
                }
                
            }

        }
        public void Chat2(string message)
        {
            foreach (NetworkStream userOnly in TableManager.Instance.Tables[TableNumber].Partners)
            {
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(message);
                userOnly.Write(buffer, 0, buffer.Length);
                buffer = new byte[1024];
                userOnly.Read(buffer, 0, buffer.Length);
                userOnly.Flush();

            }
        }
        public void ChatTcp(string message)
        {
            foreach (NetworkStream userOnly in TableManager.Instance.Tables[TableNumber].Partners)
            {
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(message);
                userOnly.Write(buffer, 0, buffer.Length);
                userOnly.Flush();
                buffer = new byte[1024];
                userOnly.Read(buffer, 0, buffer.Length);
                
            }
        }
        public void Chat(string message)
        {
            
            foreach (NetworkStream userOnly in TableManager.Instance.Tables[TableNumber].Partners)
            {
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(message);
                userOnly.Write(buffer, 0, buffer.Length);
                userOnly.Flush();

            }
        }

        public void SendCards(string message)
        {
            int index = 0;
            foreach (NetworkStream userOnly in TableManager.Instance.Tables[TableNumber].CardStream)
            {
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(message);
                userOnly.Write(buffer, 0, buffer.Length);
                userOnly.Flush();
                buffer = new byte[1024];
                if (message.Split(' ')[0]!="03"&&TableManager.Instance.Tables[0].ActualCard == 0)
                {
                    string[] list = message.Split(' ');
                    TableManager.Instance.Tables[0].CardsOfUser[index] = list[2] + " " + list[3] + " " + list[4] + " " + list[5];
                    index+=1;
                    message = "02 " + TableManager.Instance.Tables[0].ActualCard + " " + TableManager.Instance.Tables[0].PullCard() + " " + TableManager.Instance.Tables[0].PullCard();
                }
               buffer = new byte[1024];
                userOnly.Read(buffer, 0, buffer.Length);
                
            }

        }

        public void NextCardByUser()
        {
            foreach (NetworkStream userOnly in TableManager.Instance.Tables[TableNumber].Partners)
            {
                byte[] buffer1 = UserToByteArray(TableManager.Instance.Tables[TableNumber].PullCard());
                userOnly.Write(buffer1, 0, buffer1.Length);
                userOnly.Flush();

                byte[] buffer2 = UserToByteArray(TableManager.Instance.Tables[TableNumber].PullCard());
                userOnly.Write(buffer2, 0, buffer2.Length);
                userOnly.Flush();
            }
        }

        public void NextCardByTable()
        {
            foreach (NetworkStream userOnly in TableManager.Instance.Tables[TableNumber].Partners)
            {
                byte[] buffer = UserToByteArray(TableManager.Instance.Tables[TableNumber].PullTableCard());
                userOnly.Write(buffer, 0, buffer.Length);
                userOnly.Flush();
            }
        }

        private byte[] UserToByteArray(Object userReceived)
        {
            if (userReceived == null)
            { this.Parameter = null; return null; }
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream memoryStream=null;
            try
            {
                memoryStream = new MemoryStream();
                binaryFormatter.Serialize(memoryStream, userReceived);
            }
            catch (ArgumentNullException)
            {

            }
            finally
            {
                if (memoryStream != null)
                    memoryStream.Dispose();

            }
            return memoryStream.ToArray();
        }

        public void SendReceiveAnswer()
        {
            do
            {
                string all = Receive();
                if (all != null)
                {
                    string[] words = all.Split(' ');

                    switch (words[0])
                    {
                            
                        case "01":
                            this.Parameter=((DataBase.RegisterNewUser(words[1], words[2], words[3], words[4], words[5], null)));


                            Send(this.Parameter);    


                            break;
                        case "02":
                            lock (TableManager.Instance.Mutex)
                            {
                                CommunicationOff = true;
                                if (JoinToTheTable(words[1], words[2], Convert.ToInt32(words[3], CultureInfo.InvariantCulture), Convert.ToInt32(words[4], CultureInfo.InvariantCulture), words[5]))
                                {
                                    int number = TableManager.Instance.Tables[TableNumber].Users;
                                    this.Parameter = "01 " + number.ToString(CultureInfo.InvariantCulture);
                                    Send(this.Parameter);
                                    for (int ID = 0; ID < number; ID++)
                                    {
                                        SendUser(ID);

                                    }
                                    Delete = false;
                                }
                                else
                                {
                                    this.Parameter = "00";
                                    Send(this.Parameter);
                                    Delete = true;
                                }
                            }
                                break;
                        // comunicationOff = true;     
                        case "03": //forgot pass answer and question
                            user = DataBase.GetUser(words[1]);
                            if (user == null)
                                this.Parameter = "Doesn'tFound";
                            else
                                this.Parameter = (Convert.ToInt32(user.Answer, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture) + " " + user.Question);
                                Send(this.Parameter);
                            break;
                        case "04": //forgotpass change
                            bool value = DataBase.ChangePassword(words[1], words[2]);
                            if (value)
                            {
                                this.Parameter = "Ok";
                            }
                            else
                                this.Parameter = ("Not");
                                Send(this.Parameter);
                            break;
                        case "05":
                            Collection<User> users = DataBase.GetAllUsers;


                            byte[] msgUser = UserToByteArray(users);
                            Send(msgUser.Length.ToString(CultureInfo.InvariantCulture));
                            Receive();
                            SendBytes(msgUser);
                            break;

                        case "06":
                            string word = "";
                            for (int phrase = 1; phrase < words.Length; phrase++)
                            {
                                word = word + " " + words[phrase];
                            }
                            this.Parameter = "03 "+word;
                            Chat( this.Parameter);
                            break;
                        case "07":
                            //bool userStatus = DataBase.GetStatus(words[1]);
                            //if (!userStatus)
                            {

                                user = DataBase.GetUserTwo(words[1], words[2]);
                                if (user == null)
                                {
                                    bool userStatus = DataBase.GetStatus(words[1]);
                                    if (userStatus == true)
                                    {
                                        text.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate()
                                        {
                                            this.Parameter = DateTime.Now + " " + words[1] + " made a mistake when typing your password";
                                            text.Text = this.Parameter;
                                            this.Parameter = "IncorrectPassword";
                                            Send(this.Parameter);

                                        }));
                                    }
                                    else
                                    {
                                        text.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate()
                                         {
                                             this.Parameter = DateTime.Now + " " + words[1] + " is trying to enter but that user does not exist";
                                             text.Text = this.Parameter;
                                             this.Parameter = "DoesnotFound";
                                             Send(this.Parameter);

                                         }));
                                    }
                                }
                                else
                                {
                                    if (!DataBase.IBanned(user.Name))
                                    {
                                        if (user.Status==1)
                                        {
                                              text.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                                   new Action(delegate()
                                                 {
                                                   this.Parameter=DateTime.Now + " " + words[1] + "is trying to enter two times";
                                                 text.Text = this.Parameter;
                                               this.Parameter = "statusTrue";
                                             Send(this.Parameter);

                                             }));
                                        }
                                        else
                                        {
                                            text.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                               new Action(delegate()
                                               {
                                                   this.Parameter = DateTime.Now + " " + words[1] + " was Logged on";
                                                   text.Text = this.Parameter;
                                                   this.Parameter =/* (*/user.Name + " " + user.Answer + " " + user.Email + " " + user.Question + " " + user.Password + " " + user.Chips + " " + user.Status + " " + user.UserLevel + " " + user.TimeWon/*)*/;
                                                   Send(this.Parameter);
                                                   DataBase.IncrementLog(user.Name);
                                                   DataBase.ChangeStatusUser(words[1], 1);

                                               }));
                                        }
                                    }
                                    else
                                    {
                                        this.Parameter = "you are banned,you can return "+ DataBase.ActualHour(user.Name);
                                        Send(this.Parameter);
                                    
                                    }
                                }
                            }
                            //else
                            //{
                              //  text.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                //       new Action(delegate()
                                  //     {
                                    //       this.Parameter=DateTime.Now + " " + words[1] + "is trying to enter two times";
                                      //     text.Text = this.Parameter;
                                        //   this.Parameter = "statusTrue";
                                          // Send(this.Parameter);
                            
                                      // }));
                           // }
                                break;
                        /*
                         case "07":
                        bool userStatus = DataBase.GetStatus(words[1]);
                        if (!userStatus)
                        {
                            user = DataBase.GetUserTwo(words[1], words[2]);
                            if (user == null)
                                send("DoesnotFound");
                            else
                            {
                                send(user.Name + " " + user.Answer + " " + user.Email + " " + user.Question + " " + user.Password + " " + user.Chips + " " + user.Status);
                                bool res = DataBase.ChangeStatusUser(words[1], 1);
                            }
                        }
                        else
                            send("statusTrue");
                        break;
                    case "08":
                         */
                        case "08":
                            int result = DataBase.Subtract(words[1], words[2], words[3]);
                            if (result == 1)
                                this.Parameter=( ("Doesn'tFound"));
                            else
                                if (result == 2)
                                    this.Parameter=( ("InsufficientMoney"));
                                else
                                    if (result == 3)
                                        this.Parameter=( ("AmountTransferred"));
                                    else
                                        this.Parameter=( ("oto"));

                            Send(this.Parameter);
                            break;
                        case "09":
                            float money = DataBase.GetAmount(words[1],words[2]);
                            if (money > -1)
                                Send(money.ToString(CultureInfo.InvariantCulture));
                            else
                            {
                                this.Parameter="Doesn'tFound";
                                Send(this.Parameter);
                            }
                                break;

                        case "11":
                                lock (TableManager.Instance.Mutex)
                                {
                                    bool correctAnwer = DataBase.SendRequest(words[1], words[2]);
                                    if (correctAnwer)
                                        this.Parameter = "ok";
                                    else
                                        this.Parameter = "NOT";
                                    Send(this.Parameter);
                                }
                            break;
                        case "12":
                            Collection<UserContacts> directory = new Collection<UserContacts>();
                            directory = DataBase.GetUserContacts(words[1]);
                            byte[] bytes = UserToByteArray(directory);
                            Send(bytes.Length.ToString(CultureInfo.InvariantCulture));
                            Receive();
                            SendBytes(bytes);
                            break;
                        case "13":
                            bool correct = DataBase.ChangeStatus(words[1], words[2], words[3]);
                            if (correct)
                                this.Parameter="ok";
                            else
                                this.Parameter="not";
                                Send(this.Parameter);
                            break;
                        case "14":
                            DataBase.SetChips(words[1],Convert.ToInt64(words[2],CultureInfo.InvariantCulture));
                            if(words.Length>3)
                                DataBase.SetLevelTimeWon(words[1], Convert.ToInt32(words[3], CultureInfo.InvariantCulture), Convert.ToInt64(words[4], CultureInfo.InvariantCulture));
                            this.Parameter = "Complete";
                            Send(this.Parameter);

                            break;
                        case "15":
                            if (TableManager.Instance.Tables[TableNumber].LastBet == words[1])
                            {
                                int indexReceived= TableManager.Instance.Tables[TableNumber].UserTable.IndexOf(words[1]);
                                indexReceived++;
                                if (indexReceived >= TableManager.Instance.Tables[TableNumber].Users)
                                    indexReceived = 0;
                                TableManager.Instance.Tables[TableNumber].SetLastBet(TableManager.Instance.Tables[TableNumber].UserTable[indexReceived]);
                                //TODO cambiar al momento de retirarse
                            }

                            LeaveTable(words[1]);
                       //     this.Parameter = (" ");
                         //   Send( this.Parameter);


                       //     comunicationOff = true;
                            break;
                        /*
                        case "20":
                            Send( ("ok"));
                            Byte[] array = ReceiveImage(Convert.ToInt32(words[1], CultureInfo.InvariantCulture));
                            User newUSer = new User();
                            newUSer = (User)ByteArrayToUser(array);
                            if (DataBase.EditUser(newUSer))
                                Send( ("01"));
                            else
                                Send( ("00"));
                            break;
                        */

                        //Insert Transaction
                        case "16":
                            if (DataBase.GetGameStatus(words[1], words[2], DateTime.Now.ToString(CultureInfo.InvariantCulture).Replace(' ', '_')))
                               this.Parameter=("01");
                            else
                                this.Parameter=("00");
                            Send(this.Parameter);
                            break;
                        case "17":
                            DataBase.SetGameStatus(words[1], words[2], DateTime.Now.AddDays(1).ToString(CultureInfo.InvariantCulture).Replace(' ', '_'));
                            this.Parameter = "Complete";
                            Send(this.Parameter);
                            break;
                        case "18": //first time, start game

                            TableManager.Instance.Tables[0].SetStart(true);
                            TableManager.Instance.Tables[TableNumber].SetLastBet(TableManager.Instance.Tables[TableNumber].UserTable[0]);
                            TableManager.Instance.Tables[TableNumber].SetStatus(true);
                            this.Parameter = "08";
                            Chat(this.Parameter);
                            SendTheHand();
                            this.Parameter = "0";
                            YourTurnBet(this.Parameter);
                            
                            break;
                        case "19": // pass
                            lock (TableManager.Instance.Mutex)
                            {
                                this.Parameter = "Next";
                                Send(this.Parameter);
                            
                                string NameStart = TableManager.Instance.Tables[TableNumber].GetStartName;
                                TableManager.Instance.Tables[TableNumber].Next();

                                VerifyPass = words[1];
                                int indexPass = TableManager.Instance.Tables[0].UserTable.IndexOf(NameStart);
                                TableManager.Instance.Tables[0].UsersBet[indexPass] -= TableManager.Instance.Tables[0].TurnBet[indexPass];
                                TableManager.Instance.Tables[0].TurnBet[indexPass] = Convert.ToInt64(words[1], CultureInfo.CurrentCulture);
                          //      TableManager.Instance.Tables[0].Chips[indexPass] = (Convert.ToInt64(TableManager.Instance.Tables[0].Chips[indexPass],CultureInfo.InvariantCulture)-Convert.ToInt64(words[1], CultureInfo.CurrentCulture)).ToString(CultureInfo.InvariantCulture);
                                TableManager.Instance.Tables[0].UsersBet[indexPass] += Convert.ToInt64(words[1], CultureInfo.CurrentCulture);
                              
                                resetAllBet(NameStart,words[2]);
                     
                                YourTurnBet(VerifyPass);
                                }
                            break;
                        case "20"://bet
                            lock (TableManager.Instance.Mutex)
                            {

                                Bet(words);
                            }
                                break;
                        case "21":
                            this.Parameter = "07";
                            NetworkStream auxiliar = TableManager.Instance.Tables[TableNumber].Partners[0];
                            TableManager.Instance.Tables[TableNumber].Partners.Remove(auxiliar);
                            TableManager.Instance.Tables[TableNumber].Partners.Add(auxiliar);

                            Chat(this.Parameter);
                            TableManager.Instance.Tables[TableNumber].Reset();
            
                            break;
                        case "22":
                            Address = words[1] + " " + words[2] + " " + words[3] + " " + words[4] + " " + words[5] + " " + words[6] + " " + words[7];
                            TableManager.Instance.ActualGames.Add(Address);
                            this.Parameter = "00 "+words[1]+" "+words[2]+" "+words[3]+" "+words[4]+" "+words[5]+" "+words[6]+" "+words[7];
                            NotifyAll(this.Parameter);
                            //avisa a un usuario las nuevas partidas
                            break;
                        case "23":
                            TableManager.Instance.AllGames.Add(ClientStream);
                            this.Parameter = "received";
                            Send(this.Parameter);
                            break;
                        case "24":
                            this.Parameter ="01 "+ Address;
                            TableManager.Instance.ActualGames.Remove(Address);
                            NotifyAll(this.Parameter);
                            break;
                        case "25":
                            TableManager.Instance.AllGames.Remove(ClientStream);
                            
                            break;
                        case "26":
                            //envia todas las partidas disponibles a un usuario nuevo
                            this.Parameter = TableManager.Instance.ActualGames.Count.ToString(CultureInfo.InvariantCulture);
                            Send(this.Parameter);
                            Receive();
                            foreach (string game in TableManager.Instance.ActualGames)
                            {
                                
                                this.Parameter = game;
                                Send(this.Parameter);
                                Receive();
                            }
                            break;
                        case "27": // Send all database levels 
                            Collection<LevelDatabase> levels = DataBase.GetAllLevels;
                            bytes = UserToByteArray(levels);
                            Send(Convert.ToString(bytes.Length,CultureInfo.InvariantCulture));
                            Receive();
                            SendBytes(bytes);
                            break;
                        case "28":
                            SendTableUsers();
                            break;
                        case "30":
                            {
                                
                                this.Parameter = ("Ok");
                                Send(this.Parameter);
                                if (DataBase.GetUser(words[1]) != null && DataBase.GetUser(words[2]) != null)
                                {
                                    DataAccessTransaction DataTransaction = new DataAccessTransaction();
                                    if (DataTransaction.InsertTransaction(words[1], words[2], Convert.ToInt64(words[3], CultureInfo.InvariantCulture)) == true)
                                    {
                                        long AmountToUser = DataBase.GetChips(words[2]);
                                        long AmountToUserToAdd = Convert.ToInt64(words[3], CultureInfo.InvariantCulture);
                                        long AmountFromUser = Convert.ToInt64(words[4], CultureInfo.InvariantCulture);

                                        if (AmountToUser == -1)
                                        {
                                            this.Parameter = ("01");
                                            Send(this.Parameter); //It is false  
                                        }

                                        if (DataBase.SetChips(words[2], AmountToUser + AmountToUserToAdd) == true &&
                                            DataBase.SetChips(words[1], AmountFromUser) == true)
                                        {
                                            this.Parameter = ("00");
                                            Send(this.Parameter); //It is true
                                        }
                                        else
                                        {
                                            this.Parameter = ("01");
                                            Send(this.Parameter); //It is false 
                                        }
                                    }
                                }
                                else
                                {
                                    this.Parameter = ("02");
                                    Send(this.Parameter); //No user name found                             
                                }
                            }
                            break;

                        //Transaction Both
                        case "31":
                            {
                                Collection<Transaction> ListBothTransaction = new Collection<Transaction>();
                                DataAccessTransaction DataTransaction = new DataAccessTransaction();
                                ListBothTransaction = DataTransaction.GetBothTransaction(words[1]);
                                byte[] Bytes = UserToByteArray(ListBothTransaction);
                                Send(Bytes.Length.ToString(CultureInfo.InvariantCulture));
                                Receive();
                                SendBytes(Bytes);
                            }
                            break;

                        //Transaction Received
                        case "32":
                            {
                                Collection<Transaction> ListReceivedTransaction = new Collection<Transaction>();
                                DataAccessTransaction DataTransaction = new DataAccessTransaction();
                                ListReceivedTransaction = DataTransaction.GetReceivedTransaction(words[1]);
                                byte[] Bytes = UserToByteArray(ListReceivedTransaction);
                                Send(Bytes.Length.ToString(CultureInfo.InvariantCulture));
                                Receive();
                                SendBytes(Bytes);
                            }
                            break;

                        //Transaction Send
                        case "33":
                            {
                                Collection<Transaction> ListSendTransaction = new Collection<Transaction>();
                                DataAccessTransaction DataTransaction = new DataAccessTransaction();
                                ListSendTransaction = DataTransaction.GetSendTransaction(words[1]);
                                byte[] Bytes = UserToByteArray(ListSendTransaction);
                                Send(Bytes.Length.ToString(CultureInfo.InvariantCulture));
                                Receive();
                                SendBytes(Bytes);
                            }
                            break;
                        case "34": // retire
                            lock (TableManager.Instance.Mutex)
                            {
                                int indexName = TableManager.Instance.Tables[TableNumber].UserTable.IndexOf(words[1]);
                                TableManager.Instance.Tables[TableNumber].SetState(indexName, false);
                                TableManager.Instance.Tables[TableNumber].Next();
                                VerifyPass = words[2];
                                resetAll();
                                verifyIfLastBet(words[1]);
                                this.Parameter2 += (" " + TableManager.Instance.Tables[TableNumber].UserTable[indexName] + " retire");
                                ChatTcp(this.Parameter2);
                                YourTurnBet(VerifyPass);
                               
                            }
                                break;
                        case "35": // me estoy retirando y es mi turno
                            LeaveTable(words[2]);
                            if (TableManager.Instance.Tables[TableNumber].Users == TableManager.Instance.Tables[TableNumber].Start)
                            {
                                TableManager.Instance.Tables[TableNumber].Next();
                            }
                            resetAll();
                           // this.Parameter = this.Parameter = "09 " + TableManager.Instance.Tables[TableNumber].UserTable[TableManager.Instance.Tables[TableNumber].Start];
                            Parameter2 += (" "+words[2] + " retire"); 
                           ChatTcp(Parameter2);
                           YourTurnBet(words[1]);
                           
                           break;
                        case "36":
                            
                            Chat(Resources.messageTen+words[1]);
                            break;
                        case "40":
                            bool successfulChange = DataBase.ChangeAmount(words[1], words[2], words[3], words[4]);
                            if (successfulChange)
                               this.Parameter=( ("true"));
                            else
                                this.Parameter=( ("false"));

                            Send(this.Parameter);
                            break;
                        case "41":
                            bool correctRegister = DataBase.RegisterNewUserCreditCard(words[1], words[2]);
                            if (correctRegister)
                                this.Parameter=( ("ok"));
                            else
                                this.Parameter=( ("not"));
                            Send(this.Parameter);
                            break;
                        case "42":
                            bool resultLogIn = DataBase.LogOnUserCreditCard(words[1], words[2]);
                            if (resultLogIn)
                               this.Parameter=("yes");
                            else
                                this.Parameter=("no");
                            Send(this.Parameter);
                            break;
                        case "43":
                            bool resultChangeStatus = DataBase.ChangeStatusUser(words[1], Convert.ToInt16(words[2], CultureInfo.InvariantCulture));
                            if (resultChangeStatus)
                            {
                                   text.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                   new Action(delegate()
                                   {
                                       this.Parameter=DateTime.Now + " " + words[1] + " was Logged out";
                                       text.Text = this.Parameter;
                                       BannedUsers.Instance.RetireUser(words[1].ToUpperInvariant());
                                   }));

                                   
                            }
                            
                            Send(resultChangeStatus.ToString());
                            break;
                        case "70":
                            BannedUsers.Instance.AddUser(words[1], ClientStream);
                            break;
                        case "71":
                            this.Parameter = DateTime.Now.ToString(CultureInfo.InvariantCulture);
                            Send(this.Parameter);
                            break;
                        case "91":
                            string userLoan = DataBase.LoanStatusUser(words[1]);
                            Send(userLoan);
                            break;
                        case "92":
                            bool resultLoan = DataBase.LoanSetUser(words[1],words[2]);
                            Send(resultLoan.ToString());
                            break;
                        case "93":
                            bool resultDelete = DataBase.LoanDelete(words[1]);
                            Send(resultDelete.ToString());
                            break;
                        case "97":
                            bool resultfour = DataBase.RemoveDeck(words[1], Convert.ToInt32(words[2], CultureInfo.InvariantCulture));
                            Send(resultfour.ToString());
                            break;
                        case "98":
                            string getUserDecks = DataBase.GetDeck(words[1]);
                            Send(getUserDecks);
                            break;
                        case "99":
                            bool setUserDeck = DataBase.SetDeck(words[1], Convert.ToInt32(words[2], CultureInfo.InvariantCulture));
                            Send(setUserDeck.ToString());
                            break;
                        /*case "42":
                            bool resultLogIn = DataBase.LogOnUserCreditCard(words[1],words[2]);
                            break;
                        case "42":
                            string content = DataBase.getUserCreditCard(words[1], words[2],words[3]);
                            send(content);
                            break;*/
                        case "47":
                            Collection<User> hands = DataBase.GetAllHands;

                            byte[] msgHands = UserToByteArray(hands);
                            Send(msgHands.Length.ToString(CultureInfo.InvariantCulture));
                            Receive();
                            SendBytes(msgHands);
                            break;

                        case "77":
                            string amount = Convert.ToString(DataBase.BestHand(words[1]),CultureInfo.InvariantCulture);
                            Send(amount);
                            break;
                    }
                }
            } while (!CommunicationOff);

        }

        private void Bet(string[] words)
        {
            SetNewBet();
            string StartName = TableManager.Instance.Tables[TableNumber].GetStartName;
            int indexBet = TableManager.Instance.Tables[0].UserTable.IndexOf(StartName);
            //TableManager.Instance.Tables[0].Chips[indexBet] = (Convert.ToInt64(TableManager.Instance.Tables[0].Chips[indexBet], CultureInfo.InvariantCulture) - Convert.ToInt64(words[2], CultureInfo.CurrentCulture)).ToString(CultureInfo.InvariantCulture);
            TableManager.Instance.Tables[0].UsersBet[indexBet] -= TableManager.Instance.Tables[0].TurnBet[indexBet];
            TableManager.Instance.Tables[0].TurnBet[indexBet] = Convert.ToInt64(words[2], CultureInfo.CurrentCulture);
           
            TableManager.Instance.Tables[0].UsersBet[indexBet] += Convert.ToInt64(words[2], CultureInfo.CurrentCulture);

            TableManager.Instance.Tables[TableNumber].Next();
            int indexStart = TableManager.Instance.Tables[TableNumber].Start;
            //si se tira aca estaba el YourTurnBet(words[2]); y no abajo  
            this.Parameter = "09 " + TableManager.Instance.Tables[TableNumber].UserTable[indexStart] + " " + StartName + " " + words[2];
            Chat(this.Parameter);
            YourTurnBet(words[2]);
        }
        private void SendTheHand()
        {
            string card1 = TableManager.Instance.Tables[0].PullCard().ToString();
            string card2 = TableManager.Instance.Tables[0].PullCard().ToString();
            this.ParameterCard = "02 " + TableManager.Instance.Tables[0].ActualCard + " " +card1 + " " + card2;
            SendCards(this.ParameterCard); 
            TableManager.Instance.Tables[0].NextCard();
            TableManager.Instance.Tables[0].NextCard();
        }
        private void SetNewBet()
        {
            int number = TableManager.Instance.Tables[TableNumber].Start;
            TableManager.Instance.Tables[TableNumber].SetLastBet(TableManager.Instance.Tables[TableNumber].UserTable[number]);
        }
        public bool TheLastBet()
        { 
            int number=TableManager.Instance.Tables[TableNumber].Start;

            return (TableManager.Instance.Tables[TableNumber].LastBet == TableManager.Instance.Tables[TableNumber].UserTable[number]);
        
        }
        private bool VeryfyTurn()
        {
            if (TheLastBet())
            {
                TableManager.Instance.Tables[0].ResetTurnBet();
                TableManager.Instance.Tables[0].DecreaseMyChips();
                
                VerifyPass = "0";
                TableManager.Instance.Tables[TableNumber].NextTurn();
                TableManager.Instance.Tables[TableNumber].SetLastBet(TableManager.Instance.Tables[TableNumber].UserTable[TableManager.Instance.Tables[TableNumber].Start]);
                int index = TableManager.Instance.Tables[TableNumber].Start;
                this.Parameter2 = "11 " + TableManager.Instance.Tables[TableNumber].Turn + " " + TableManager.Instance.Tables[TableNumber].UserTable[index];
                if (TableManager.Instance.Tables[0].ActualCard < 7)
                {
                    string card1 = TableManager.Instance.Tables[0].PullCard().ToString();
                    this.ParameterCard = "01 " + TableManager.Instance.Tables[0].ActualCard + " " + card1;
                    //anadir CardsOfTable
                    TableManager.Instance.Tables[TableNumber].CardsOfTable.Add(card1);
                    SendCards(this.ParameterCard);
                    TableManager.Instance.Tables[0].NextCard();
                    if (TableManager.Instance.Tables[0].ActualCard == 3)
                    {
                        card1 = TableManager.Instance.Tables[0].PullCard().ToString();
                        string card2 = TableManager.Instance.Tables[0].PullCard().ToString();
                        this.ParameterCard = "02 " + TableManager.Instance.Tables[0].ActualCard + " " + card1 + " " + card2; 
                        //anadir CardsOfTable
                        TableManager.Instance.Tables[TableNumber].CardsOfTable.Add(card1);
                        TableManager.Instance.Tables[TableNumber].CardsOfTable.Add(card2);
                        TableManager.Instance.Tables[0].NextCard();
                        TableManager.Instance.Tables[0].NextCard();

                        SendCards(this.ParameterCard);

                    }
                }
                
                
            }
            else
            {
                int index = TableManager.Instance.Tables[TableNumber].Start;
                this.Parameter2 = "09 " + TableManager.Instance.Tables[TableNumber].UserTable[index] ;
            }
          if (TableManager.Instance.Tables[TableNumber].Turn == 4)
              return true;
          return false;
        }
        private void resetAll()
        {
            if (VeryfyTurn() || TableManager.Instance.Tables[TableNumber].OnlyOneOnTable() )
            {
                VerifyPass = "0";
                TableManager.Instance.Tables[TableNumber].NextDealer();
                
                int index = TableManager.Instance.Tables[TableNumber].Start;
                this.Parameter2 = "11 " + TableManager.Instance.Tables[TableNumber].Turn + " " + TableManager.Instance.Tables[TableNumber].UserTable[index];
                TableManager.Instance.Tables[0].ResetCardNumber();
                
                string result;
                string[] winnerAndHand;
                winnerAndHand = new string[2];
                bool res = false;
                
                if (TableManager.Instance.Tables[TableNumber].OnlyOneOnTable())
                {
                     result = TableManager.Instance.Tables[TableNumber].GetOnlyOneUserInTable.ToString(CultureInfo.InvariantCulture);
                     res = true;
                }
                else
                {
                    LogicalWinner.LogicalWinnerUser.Instance.PointerUsers = 0;
                    string totalCardsOfTable = "";
                    string totalCardsOfUser = "";
                    for (int i = 0; i < 5; i++)
                    {
                        totalCardsOfTable = totalCardsOfTable + " " + TableManager.Instance.Tables[TableNumber].CardsOfTable[i];
                        if (TableManager.Instance.Tables[TableNumber].CardsOfUser[i] != null)
                        {
                            totalCardsOfUser = totalCardsOfUser + " " + TableManager.Instance.Tables[TableNumber].CardsOfUser[i];
                        }
                    }
                    //TODO verificar ganador
                    LogicalWinner.LogicalWinnerUser.Instance.ConvertCards(totalCardsOfTable, totalCardsOfUser);
                    LogicalWinner.LogicalWinnerUser.Instance.GetWinner();
                    
                    result = LogicalWinner.LogicalWinnerUser.Instance.WinnerInHands;
                    winnerAndHand = result.Split(' ');
                    //TODO repartir nuevas cartas
                    TableManager.Instance.Tables[0].ResetCardsOfUser(); 
                }
                TableManager.Instance.Tables[TableNumber].ResetTurn();
                TableManager.Instance.Tables[TableNumber].ResetStates();
                long price=TableManager.Instance.Tables[0].GetPrice;
                TableManager.Instance.Tables[TableNumber].Chips[Convert.ToInt16(winnerAndHand[0], CultureInfo.InvariantCulture)] = (Convert.ToInt64(TableManager.Instance.Tables[TableNumber].Chips[Convert.ToInt16(winnerAndHand[0], CultureInfo.InvariantCulture)], CultureInfo.InvariantCulture) + price).ToString(CultureInfo.InvariantCulture);

                if (res)
                    this.ParameterCard = "03 " + result + " " + price + " only";//Nro Ganador    
                else
                    this.ParameterCard = "03 " + winnerAndHand[0] + " " + price + " " + WinnerHandValue(winnerAndHand[1]);//Nro Ganador    
                
                Query.NewHand(TableManager.Instance.Tables[TableNumber].UserTable[Convert.ToInt16(winnerAndHand[0], CultureInfo.InvariantCulture)], price);
                
                SendCards(this.ParameterCard);
                //Thread.Sleep(5000);
                
                SendTheHand();
            }
        }




        private void resetAllBet(string name,string money)
        {
            bool enter = false;
            if (VeryfyTurn() || TableManager.Instance.Tables[TableNumber].OnlyOneOnTable())
            {
                TableManager.Instance.Tables[0].ResetTurnBet();
                enter = true;
                VerifyPass = "0";
                TableManager.Instance.Tables[TableNumber].NextDealer();

                int index = TableManager.Instance.Tables[TableNumber].Start;
                this.Parameter2 = "11 " + TableManager.Instance.Tables[TableNumber].Turn + " " + TableManager.Instance.Tables[TableNumber].UserTable[index];
                TableManager.Instance.Tables[0].ResetCardNumber();
                
                string result;
                string[] winnerAndHand;
                winnerAndHand = new string[2];
                bool res = false;
                
                if (TableManager.Instance.Tables[TableNumber].OnlyOneOnTable())
                {
                    result = TableManager.Instance.Tables[TableNumber].GetOnlyOneUserInTable.ToString(CultureInfo.InvariantCulture);
                    res = true;
                }
                else
                {
                    LogicalWinner.LogicalWinnerUser.Instance.PointerUsers = 0;
                    string totalCardsOfTable = "";
                    string totalCardsOfUser = "";
                    for (int i = 0; i < 5; i++)
                    {
                        totalCardsOfTable = totalCardsOfTable + " " + TableManager.Instance.Tables[TableNumber].CardsOfTable[i];
                        if (TableManager.Instance.Tables[TableNumber].CardsOfUser[i] != null)
                        {
                            totalCardsOfUser = totalCardsOfUser + " " + TableManager.Instance.Tables[TableNumber].CardsOfUser[i];
                        }
                    }
                    //TODO verificar ganador
                    LogicalWinner.LogicalWinnerUser.Instance.ConvertCards(totalCardsOfTable, totalCardsOfUser);
                    LogicalWinner.LogicalWinnerUser.Instance.GetWinner();
                    
                    result = LogicalWinner.LogicalWinnerUser.Instance.WinnerInHands;
                    winnerAndHand = result.Split(' ');                 
                    //TODO repartir nuevas cartas
                    TableManager.Instance.Tables[0].ResetCardsOfUser();
                }
                TableManager.Instance.Tables[TableNumber].ResetTurn();
                TableManager.Instance.Tables[TableNumber].ResetStates();
                long price = TableManager.Instance.Tables[0].GetPrice;
                TableManager.Instance.Tables[TableNumber].Chips[Convert.ToInt16(winnerAndHand[0], CultureInfo.InvariantCulture)] = (Convert.ToInt64(TableManager.Instance.Tables[TableNumber].Chips[Convert.ToInt16(winnerAndHand[0], CultureInfo.InvariantCulture)], CultureInfo.InvariantCulture) + price).ToString(CultureInfo.InvariantCulture);
                this.Parameter2 = this.Parameter2 + " " + name + " " + money;
                ChatTcp(this.Parameter2);

                if (res)
                    this.ParameterCard = "03 " + result + " " + price + " only";//Nro Ganador    
                else
                    this.ParameterCard = "03 " + winnerAndHand[0] + " " + price + " " + WinnerHandValue( winnerAndHand[1]);//Nro Ganador
                
                Query.NewHand(TableManager.Instance.Tables[TableNumber].UserTable[Convert.ToInt16(winnerAndHand[0],CultureInfo.InvariantCulture)], price);

                SendCards(this.ParameterCard);
                //Thread.Sleep(5000);

                SendTheHand();
            }
            if (!enter)
            {
                this.Parameter2 = this.Parameter2 + " " + name + " " + money;
                ChatTcp(this.Parameter2);
              
            }
        }



        private string WinnerHandValue(string value)
        {
            switch (value)
            {
                case "15":
                    CaseSwitchGlobal = "OnePair";
                    return CaseSwitchGlobal;
                case "16":
                    CaseSwitchGlobal = "TwoPair";
                    return CaseSwitchGlobal;
                case "17":
                    CaseSwitchGlobal = "ThreeOfTheKing";
                    return CaseSwitchGlobal;
                case "18":
                    CaseSwitchGlobal = "Straight";
                    return CaseSwitchGlobal;
                case "19":
                    CaseSwitchGlobal = "Flush";
                    return CaseSwitchGlobal;
                case "20":
                    CaseSwitchGlobal = "FullHouse";
                    return CaseSwitchGlobal;
                case "21":
                    CaseSwitchGlobal ="Poker";
                    return CaseSwitchGlobal;
                case "22":
                    CaseSwitchGlobal="StraightFlush";
                    return CaseSwitchGlobal;
                case "23":
                    CaseSwitchGlobal ="RoyalFlush";
                    return CaseSwitchGlobal;
                case "only":
                    CaseSwitchGlobal="Default";
                    return CaseSwitchGlobal;

            }
            CaseSwitchGlobal = "HighCard";
            return CaseSwitchGlobal;
        }

        private static void NotifyAll(string message)
        {
            foreach (NetworkStream userOnly in TableManager.Instance.AllGames)
            {
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(message);
                userOnly.Write(buffer, 0, buffer.Length);
                userOnly.Flush();

            }
        }

        public void YourTurn()
        {
            ASCIIEncoding encoder = new ASCIIEncoding();
            this.Parameter = "05 "+TableManager.Instance.Tables[0].GetMinimum;
           byte []bytes=encoder.GetBytes(this.Parameter);
            TableManager.Instance.Tables[TableNumber].Partners[TableManager.Instance.Tables[TableNumber].Start].Write(bytes,0,bytes.Length);
            TableManager.Instance.Tables[TableNumber].Partners[TableManager.Instance.Tables[TableNumber].Start].Flush();
            bytes=new byte[1024];
            TableManager.Instance.Tables[TableNumber].Partners[TableManager.Instance.Tables[TableNumber].Start].Read(bytes,0,bytes.Length);                          
        }
        private void YourTurnBet(string Bet)
        {
            lock (TableManager.Instance.Mutex)
            {
                if (TableManager.Instance.Tables[TableNumber].Partners.Count > 0)
                {
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    this.Parameter = "06 " + Bet+" "+TableManager.Instance.Tables[0].GetMinimum;
                    byte[] bytes = encoder.GetBytes(this.Parameter);
                    TableManager.Instance.Tables[TableNumber].Partners[TableManager.Instance.Tables[TableNumber].Start].Write(bytes, 0, bytes.Length);
                    TableManager.Instance.Tables[TableNumber].Partners[TableManager.Instance.Tables[TableNumber].Start].Flush();
                    bytes = new byte[1024];
                    TableManager.Instance.Tables[TableNumber].Partners[TableManager.Instance.Tables[TableNumber].Start].Read(bytes, 0, bytes.Length);
                }
            }
        }
        
        
        void Move(int chair)
        {
            int number = TableManager.Instance.Tables[TableNumber].Users;
            for (int moving = chair; moving<number; moving++)
            {
                TableManager.Instance.Tables[TableNumber].UserTable[moving] = TableManager.Instance.Tables[TableNumber].UserTable[moving + 1];
                TableManager.Instance.Tables[TableNumber].Chips[moving] = TableManager.Instance.Tables[TableNumber].Chips[moving + 1];
                TableManager.Instance.Tables[TableNumber].Level[moving] = TableManager.Instance.Tables[TableNumber].Level[moving + 1];
                TableManager.Instance.Tables[TableNumber].TimeHandsWon[moving] = TableManager.Instance.Tables[TableNumber].TimeHandsWon[moving + 1];
            }
            TableManager.Instance.Tables[TableNumber].UserTable[number] = "";
            TableManager.Instance.Tables[TableNumber].Chips[number] = "";
         }
        private void LeaveTable(string name)
        {
            lock (TableManager.Instance.Mutex)
            {
                
                int Index = TableManager.Instance.Tables[TableNumber].UserTable.IndexOf(name);

                if (TableManager.Instance.Tables[TableNumber].Partners.Count > 0)
                {

                    TableManager.Instance.Tables[TableNumber].Partners.Remove(TableManager.Instance.Tables[TableNumber].Partners[Index]);
                    
                    //chatPartners.Remove(chatPartners[Index]);
                    TableManager.Instance.Tables[TableNumber].Users--;
                    string Auxiliar = TableManager.Instance.Tables[TableNumber].UserTable[Index];
                    Move(Index);
                    byte[] buffer;
                    TableManager.Instance.Tables[TableNumber].UsersBet.Remove(TableManager.Instance.Tables[TableNumber].UsersBet[Index]);
                    TableManager.Instance.Tables[TableNumber].CardStream.Remove(TableManager.Instance.Tables[TableNumber].CardStream[Index]);
                    foreach (NetworkStream UserInTable in TableManager.Instance.Tables[TableNumber].Partners)
                    {
                        ASCIIEncoding encoder = new ASCIIEncoding();
                        buffer = encoder.GetBytes("02 " + Auxiliar + " " + Index);
                        UserInTable.Write(buffer, 0, buffer.Length);
                        UserInTable.Flush();
                    }
                }
            }
        }
        private void verifyIfLastBet(string name)
        {
            if (TableManager.Instance.Tables[TableNumber].LastBet == name)
            {
                TableManager.Instance.Tables[TableNumber].SetLastBet(TableManager.Instance.Tables[TableNumber].UserTable[TableManager.Instance.Tables[TableNumber].Start]);
            }
        }
        private void SendTableUsers()
        {
                int number = TableManager.Instance.Tables[TableNumber].Users;
                Send(number.ToString(CultureInfo.InvariantCulture));
                for (int ID = 0; ID < number; ID++)
                {
                    SendUser(ID);

                }
        }
}
}
